<template>
  <div>
    <div>
      <!--header-->
      <el-row :gutter="20">
        <el-col :span="3">
          <div class="top5">
            <p class="top-text">周报筛选: </p>
          </div>
        </el-col>
        <!--下拉-->
        <el-col :span="6">
          <div class="top5">
            <el-dropdown @command="handleGroupChange">
          <span class="el-dropdown-link top-text blue-text">
            {{curGroupName}}<i class="el-icon-caret-bottom el-icon--right"></i>
          </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="item.id" v-for="item in myGroups" :key="item.id">{{item.name}}
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </el-col>
        <!--日历-->
        <el-col :span="6">
          <div style="margin-left: 55px">
            <el-date-picker
              v-model="week"
              type="week"
              format="yyyy 年 第 WW 周"
              placeholder="选择周"
              :readonly="true"
              :picker-options="options"
            >
            </el-date-picker>
          </div>
        </el-col>
      </el-row>
    </div>

    <!--markdown + upload-->
    <div class="div-margin20 grayBoundTop20">
      <!--markdown editor-->
      <div id="editor" style="padding-left: 5px;padding-right: 5px">
        <mavon-editor
          v-model="markdown_value"
          default_open="edit"
          :subfield="false"
          :toolbars="toolbars"
          @change="markChange"
          style="height: 100%"></mavon-editor>
      </div>
      <!--upload-->
      <el-row>
        <el-col :span="12">
          <div style="width: 300px; padding-left: 10px;margin: 20px 0px">
            <el-upload
              class="upload-demo"
              :action="uploadUrl"
              name="file"
              :on-success="handleFileUploadSuccess"
              :on-remove="handleFileUploadRemove"
              :on-error="handleUploadError"
              :file-list="uploadFileList">
              <el-button size="small" type="primary">添加附件</el-button>
              <div slot="tip" class="el-upload__tip" v-show="uploadFileList.length>0">文件列表</div>
            </el-upload>
          </div>
        </el-col>
        <el-col :span="12" align="right">
          <div style="padding-right: 10px;margin: 20px 0">
            <el-button type="success" @click="submit">提交</el-button>
          </div>
        </el-col>
      </el-row>


    </div>

    <!--preview of before-->
    <div class=" grayBoundTop20 post_preview_container" v-for="(item,index) in history_post">
      <post :content="item.content" :date="item.createTime" :attachments="item.attachments"></post>
    </div>

  </div>
</template>

<script>
  import * as $ from '../../utils/HHUtil';
  import * as api_group from '../../api/group';
  import * as api_post from '../../api/post';
  import {mavonEditor} from 'mavon-editor'
  import 'mavon-editor/dist/css/index.css'
  import {
    Input,
    Table,
    TableColumn,
    Dropdown,
    DropdownItem,
    DropdownMenu,
    Button,
    Row,
    Col,
    DatePicker,
    Upload
  } from 'element-ui';
  import Post from "../../components/post.vue";

  export default {
    props: {},
    components: {
      Post,
      mavonEditor,
      'el-upload': Upload,
      'el-input': Input,
      'el-table': Table,
      'el-table-column': TableColumn,
      'el-button': Button,
      'el-dropdown': Dropdown,
      'el-dropdown-item': DropdownItem,
      'el-dropdown-menu': DropdownMenu,
      'el-row': Row,
      'el-col': Col,
      'el-date-picker': DatePicker
    },
    data() {
      return {
        week: new Date(),
        uploadFileList: [],
        options: {
          firstDayOfWeek: 1,
          shortcuts: [{
            text: '本周',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '上周',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }, {
            text: '上上周',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7 * 2);
              picker.$emit('pick', date);
            }
          }],
        },
        markdown_value: '',
        html_value: '',
        history_post: [],
        groupInfo: {},
        myGroups: [],
        curGroupName: '',
        fileList: [],
        toolbars: {
          bold: true, // 粗体
          italic: true, // 斜体
          header: true, // 标题
          underline: true, // 下划线
          strikethrough: true, // 中划线
          mark: true, // 标记
          superscript: true, // 上角标
          subscript: true, // 下角标
          quote: true, // 引用
          ol: true, // 有序列表
          ul: true, // 无序列表
          link: true, // 链接
          imagelink: false, // 图片链接
          code: true, // code
          table: true, // 表格
          fullscreen: true, // 全屏编辑
          readmodel: true, // 沉浸式阅读
          htmlcode: true, // 展示html源码
          help: true, // 帮助
          /* 1.3.5 */
          undo: true, // 上一步
          redo: true, // 下一步
          trash: true, // 清空
          save: true, // 保存（触发events中的save事件）
          /* 1.4.2 */
          navigation: true, // 导航目录
          /* 2.1.8 */
          alignleft: true, // 左对齐
          aligncenter: true, // 居中
          alignright: true, // 右对齐
          /* 2.2.1 */
          subfield: true, // 单双栏模式
          preview: true, // 预览
        },
        uploadUrl: ''
      };
    },
    methods: {
      markChange(value, render) {
        this.html_value = render;
      },
      handleFileUploadSuccess(response, file, fileList) {
        console.log('上传文件', fileList);
        this.uploadFileList = fileList.map(f => {
          if ($.hasValue(f.response)) {
            return {name: f.response.data.fileName, url: f.response.data.url, id: f.response.data.id}
          } else {
            return {name: f.name, url: f.url, id: f.id};
          }
        });
      },
      handleFileUploadRemove(file, fileList) {
        console.log('移除文件', fileList);
        this.uploadFileList = fileList.map(f => {
          if ($.hasValue(f.response)) {
            return {name: f.response.data.fileName, url: f.response.data.url, id: f.response.data.id}
          } else {
            return {name: f.name, url: f.url, id: f.id};
          }
        });
      },
      handleUploadError(response, file, fileList) {
        this.$message.error("上传文件失败: " + response.errmsg);
      },
      handleGroupChange(id) {
        this.$router.push({
          name: 'post',
          params: {groupId: id, year: new Date().getUTCFullYear(), week: $.weekOfYear(new Date())}
        });
      },
      submit() {
        console.log(this.uploadFileList);
        let form = {
          groupId: this.groupId,
          content: this.html_value,
          markContent: this.markdown_value,
          attachments: this.uploadFileList.map(f => f.id)
        };
        api_post.post(form).then((data) => {
          this.refresh();
          this.$notify.success({
            title: "成 功 ！",
            message: "提交成功，这是系统的第 " + data.id + " 份周报 - "
          });
        }).catch(err => {
          this.$message.error("提交失败：" + err.errmsg);
        })
      },
      loadTemplate() {
        this.markdown_value = this.groupInfo.postTemplate;
        this.markdown_value = this.markdown_value.replace('{YYYY}', new Date().getUTCFullYear());
        this.markdown_value = this.markdown_value.replace('{WW}', this.$hhUtil.weekOfYear());
      },
      getGroupInfo() {
        api_group.getGroupInfo({id: this.groupId}).then(data => {
          this.groupInfo = data;
          this.curGroupName = this.groupInfo.name;
          this.loadTemplate();
        }).catch(err => {
          this.$message.error("获取项目组信息失败：" + err.errmsg);
        });
      },
      getMyLast5Post() {
        let form = {
          groupId: this.groupId,
        };
        api_post.getMyLast5Post(form).then(data => {
          this.history_post = data;
        }).catch(err => {
          this.$message.error("获取历史数据失败：" + err.errmsg);
        });
      },
      getMyGroupsInfo() {
        api_group.getMyGroupList().then(data => {
          this.myGroups = data;
        }).catch(err => {
          this.$message.error("获取项目列表失败：" + e.errmsg);
        })
      },
      clean() {
        this.uploadFileList = [];
        this.getGroupInfo();
      },
      refresh() {
        this.clean();
        //获取我的group
        this.getMyGroupsInfo();
        //获取本周post内容
        this.getMyLast5Post();
      }
    },
    created() {
    },
    mounted() {
      let params = this.$route.params;
      this.groupId = params.groupId;
      let host = window.location.host;
      this.uploadUrl = 'http://' + host + "/sei/upload";
      this.refresh();

    }
  }
</script>

<style>

  .gray-text {
    color: gray;
  }

  .top-text {
    font-size: 16px;
    margin-top: 0;
  }

  .blue-text {
    color: #20a0ff;
  }

  .top5 {
    margin-top: 5px;
  }

  hr {
    color: #000;
  }

  #editor {
    margin: auto;
    min-height: 300px;
  }
</style>
